import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    (config) => {
        if (store.getters.token) {
            //请求头携带token
            config.headers['x-access-token'] = getToken()
        }

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (response) => {
        // return
        const res = response.data

        // 返回的code不为1表示请求不通过
        if (!res.success) {
            if (res.code === -8) {
                // to re-login
                // MessageBox.confirm('登录超时,请重新登录', '提示', {
                //     confirmButtonText: '重新登录',
                //     type: 'warning',
                //     showCancelButton: false,
                //     closeOnClickModal: false
                // }).then(() => {
                //     store.dispatch('user/resetToken').then(() => {
                //         router.push('/login')
                //     })
                // })
            } else {
                Message({
                    message: res.message || 'Error',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return Promise.reject(new Error(res.msg || 'Error'))
        } else {
            return res
        }
    },
    (error) => {
        Message({
                message: error,
                type: 'error',
                duration: 5 * 1000
            })
            // console.log(error)
        return Promise.reject(error)
    }
)

export default service